package com.vb.ecm.web.custom.barcode;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import com.documentum.fc.client.DfQuery;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfFolder;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSysObject;
import com.documentum.fc.common.DfException;
import com.documentum.web.common.ArgumentList;
import com.documentum.web.form.Control;
import com.documentum.web.form.control.Button;
import com.documentum.web.form.control.DropDownList;
import com.documentum.web.form.control.Hidden;
import com.documentum.web.form.control.Label;
import com.documentum.web.form.control.Option;
import com.documentum.web.form.control.Text;
import com.documentum.web.form.control.databound.Datagrid;
import com.documentum.web.formext.action.ActionService;
import com.documentum.web.formext.component.Component;
import com.vb.ecm.web.custom.importcontent.CustomImportComponent;

public class BarcodeGenerator extends Component{

	/**
	 * 
	 */
	private static final Logger LOGGER = Logger.getLogger(BarcodeGenerator.class);
	private static final long serialVersionUID = -7269866978333326417L;
	
	private DropDownList branchNumList;
	private DropDownList custTypeList;
	private DropDownList custIdTypeList;
	private DropDownList docSubTypeList;
	
	private Text docId;
	private Text docName;
	private Text custId;
	private Text yearCrtd;
	
	//resource bundle
	ResourceBundle rsb;
	
	private ArrayList<String> objs;
	@SuppressWarnings("unchecked")
	private ArrayList dataBeanList = new ArrayList();
	private Label successMsg = null;
	
	//private Checkbox selectedObj;
	public IDfSession getDfSession() { 

		return super.getDfSession();
	}
	
	public void onInit(ArgumentList args) 
	{		
		try
		{
			super.onInit(args);
			LOGGER.debug("Enter into onInit(), for genetate barcode pages from browsertree node");
			//resource bundle
			rsb = ResourceBundle.getBundle("com.vb.ecm.web.custom.barcode.BarcodeConfig");
			
			//drop down lists
			branchNumList =(DropDownList)getControl("branchNum",DropDownList.class);
			custTypeList =(DropDownList)getControl("custType",DropDownList.class);
			custIdTypeList =(DropDownList)getControl("custIdType",DropDownList.class);
			docSubTypeList =(DropDownList)getControl("docSubType",DropDownList.class);
			
			//text boxes
			docId = ((Text) getControl("docId", Text.class));
			docName = ((Text) getControl("docName", Text.class));
			custId = ((Text) getControl("custId", Text.class));
			yearCrtd = ((Text) getControl("yearCrtd", Text.class));
			
			successMsg = (Label) getControl("success_msg", com.documentum.web.form.control.Label.class);
			successMsg.setLabel("");
			
			//Branch Number
			Option oppAll = new Option();
			oppAll.setValue("ALL");
			oppAll.setLabel("ALL");
			branchNumList.addOption(oppAll);
			
			IDfQuery brNoQry = new DfQuery();
			brNoQry.setDQL("select object_name from dm_cabinet where object_name like 'Branch %'");
			
			IDfCollection brNoColl = brNoQry.execute(getDfSession(), IDfQuery.DF_READ_QUERY);			
			
			while (brNoColl.next()){
				
				Option opp = new Option();
				opp.setValue(brNoColl.getString("object_name").substring(7, 10).trim());
				opp.setLabel(brNoColl.getString("object_name").substring(7, 10).trim());
				branchNumList.addOption(opp); 
			}
			
			brNoColl.close();
			
			//Customer Type
			custTypeList.addOption(oppAll); 
			
			IDfQuery custTypeQry = new DfQuery();
			custTypeQry.setDQL("select distinct cust_type from dm_dbo." + rsb.getString("DOC_LIST_TABLE_NAME"));
			
			IDfCollection custTypeColl = custTypeQry.execute(getDfSession(), IDfQuery.DF_READ_QUERY);
			
			while (custTypeColl.next()){
				
				//cust_type
				Option opp1 = new Option();
				opp1.setValue(custTypeColl.getString("cust_type"));
				opp1.setLabel(custTypeColl.getString("cust_type"));
				custTypeList.addOption(opp1);		
			}
			
			custTypeColl.close();
			
			//Doc Sub Type
			docSubTypeList.addOption(oppAll);
			
			IDfQuery docSubTypeQry = new DfQuery();
			docSubTypeQry.setDQL("select distinct doc_type from dm_dbo." + rsb.getString("DOC_LIST_TABLE_NAME"));
			
			IDfCollection docSubTypeColl = docSubTypeQry.execute(getDfSession(), IDfQuery.DF_READ_QUERY);
			
			while (docSubTypeColl.next()){	
				
				//doc_type
				Option opp3 = new Option();
				opp3.setValue(docSubTypeColl.getString("doc_type"));
				opp3.setLabel(docSubTypeColl.getString("doc_type"));
				docSubTypeList.addOption(opp3);
			}
			
			docSubTypeColl.close();			
			
			//Customer Id Type	
			custIdTypeList.addOption(oppAll);
			
			IDfQuery query = new DfQuery();
			query.setDQL("select cust_type_code, description_en from dm_dbo." + rsb.getString("CUST_ID_TYPE_TABLE_NAME"));
			
			IDfCollection col = query.execute(getDfSession(), IDfQuery.DF_READ_QUERY);
			
			while(col.next())
			{				
				Option opp2 = new Option();
				opp2.setValue(col.getString("cust_type_code")+"-"+col.getString("description_en"));
				opp2.setLabel(col.getString("cust_type_code")+"-"+col.getString("description_en"));
				custIdTypeList.addOption(opp2);				
			}
			LOGGER.debug("Exit from onInit() after loading all dropdown values");
			col.close();
			
		}catch(Exception e)
		{
			successMsg.setLabel("Error in Generating Barcode onInit(): " + e.getMessage());
			LOGGER.error("Error in Generating Barcode onInit(): " + e.getMessage());
			e.printStackTrace();
		}
	}
	
	public void onSearch(Button barcodeButton, ArgumentList arg) throws DfException
	{		
		String condString = null;
		
		try
		{	
			LOGGER.debug("Enter into onSearch()");
			successMsg.setLabel("");
			
			String queryStr = "SELECT branch_number, cust_type, cust_id_type, doc_sub_type, r_object_id, " +
					"object_name, cust_id_number, car_year_created FROM vb_los_docs WHERE ";
			
			if((branchNumList.getValue()).equals("ALL")){
				condString = "branch_number IS NOT NULL AND ";
			}else{
				condString = "branch_number = '" + branchNumList.getValue() + "' AND ";
			}
			
			if((custTypeList.getValue()).equals("ALL")){
				condString = condString + "cust_type IS NOT NULL AND ";
			}else{
				condString = condString + "cust_type = '" + custTypeList.getValue() + "' AND ";
			}
			
			if((custIdTypeList.getValue()).equals("ALL")){
				condString = condString + "cust_id_type IS NOT NULL AND ";
			}
			else{
				String custIdTypeVlu = custIdTypeList.getValue();
				String[] cust_id_type = custIdTypeVlu.split("-");
				
				condString = condString + "cust_id_type = '" + cust_id_type[0] + "' AND ";
			}
			
			if((docSubTypeList.getValue()).equals("ALL")){
				condString = condString + "doc_sub_type IS NOT NULL AND ";
			}
			else{
				condString = condString + "doc_sub_type = '" + docSubTypeList.getValue() + "' AND ";
			}
			
			if((docId.getValue()).equalsIgnoreCase("") || (docId.getValue()== null) || 
					(docId.getValue()).equalsIgnoreCase("NULL")){
				
				condString = condString + "r_object_id IS NOT NULL AND ";
			}else{
				condString = condString + "r_object_id LIKE '%" + docId.getValue() + "%' AND ";
			}
			
			if((docName.getValue()).equalsIgnoreCase("") || (docName.getValue()== null) || 
					(docName.getValue()).equalsIgnoreCase("NULL")){
				
				condString = condString + "object_name IS NOT NULL AND ";
			}else{
				condString = condString + "object_name LIKE '%" + docName.getValue() + "%' AND ";
			}
			
			if((custId.getValue()).equalsIgnoreCase("") || (custId.getValue()== null) || 
					(custId.getValue()).equalsIgnoreCase("NULL")){
				
				condString = condString + "cust_id_number IS NOT NULL AND ";
			}else{
				condString = condString + "cust_id_number LIKE '%" + custId.getValue() + "%' AND ";
			}
			
			if((yearCrtd.getValue()).equalsIgnoreCase("") || (yearCrtd.getValue()== null) || 
					(yearCrtd.getValue()).equalsIgnoreCase("NULL")){
				
				condString = condString + "car_year_created IS NOT NULL";
			}else{
				condString = condString + "car_year_created LIKE '%" + yearCrtd.getValue() + "%'";
			}		
			
			Datagrid grid = (Datagrid)getControl("usergrid", Datagrid.class);
			grid.getDataProvider().setDfSession(getDfSession());
			
			grid.getDataProvider().setQuery(queryStr + condString);
			
			grid.getDataProvider().refresh();
			LOGGER.debug("Query String Executed for onSearch() "+queryStr + condString);
			LOGGER.debug("Exit from onSearch()");
		}catch(Exception e)
		{
			e.printStackTrace();
			LOGGER.error("Error in onSearch()"+e);
		}
	}
	
	public void onGenerate(Control control,ArgumentList arg) throws DfException
	{
	 try {	
		 LOGGER.debug("Enter into  onGenerate(), After clicking Generate");
		 objs =  new ArrayList<String>();		 
		
		Hidden hidden = (Hidden) getControl("hidden", Hidden.class);	
		
		ArgumentList args = new ArgumentList();
		args.add("objectId", hidden.getValue());
		
		if(hidden.getValue()!= null && !hidden.getValue().equalsIgnoreCase("")){
			objs.add(hidden.getValue());			
		}
		
		generateBarcodePages();
		
		resetControls(hidden);
		LOGGER.debug("Exit from  onGenerate(), After calling generateBarcodePages");
		}
	 	catch (Exception e){
	 		successMsg.setLabel("Error : " + e.getMessage());
			e.printStackTrace();
		}
	}
	
	private static void resetControls(Hidden hidden) {
		LOGGER.debug("Enter into from  resetControls()");
		hidden.setValue("");
		LOGGER.debug("Exit from  resetControls()");
	}

	@SuppressWarnings("unchecked")
	private void generateBarcodePages(){
		LOGGER.debug("Enter into from  generateBarcodePages()");
		boolean isUpdate = true;
		String branchno = "";
		String custtype = "";		
		String barcodeValue = "";
		String docId = null;
		int count = 0;
		boolean flag = false, lastitem = false;		
		
		try{
			
		TestBarcodeGenerationBean reportBean = new TestBarcodeGenerationBean();
		
		if(objs.size() != 0){

		String strObj = objs.toString().replaceAll("]", "");		
		String strObj1 = strObj.substring(1, strObj.length());		
		String[] splitobjs = strObj1.split(",");		
		count = splitobjs.length;		
		
		//to check even or odd items
		if(count % 2 !=0){
			flag = true;			
		}	
		
		for(int i = 0; i < splitobjs.length; i++) {
			
			docId = splitobjs[i];			
			
			IDfQuery query= new DfQuery();
			
			query.setDQL("select branch_number, cust_type, cust_id_number, doc_sub_type, " +
					"cust_id_type from vb_los_docs where r_object_id = '"+ docId +"'");
			LOGGER.debug("Executing Query for getting dctm objects to generate barcode");
			IDfCollection coll = query.execute(getDfSession(),DfQuery.EXEC_QUERY);

			if((i == count - 1) && flag){
				lastitem = true;				
			}
			
			while(coll.next())
			{				
				branchno = coll.getString("branch_number");
				custtype = coll.getString("cust_type");								

				barcodeValue = branchno + " - " + custtype + " - " + docId.substring(8, 16);				
								
				if(isUpdate){
					reportBean=new TestBarcodeGenerationBean();					
					reportBean.setBarcodev(barcodeValue);				
					reportBean.setFirstBranch("Branch No :" + branchno);
					reportBean.setFirstCustID("Customer Id : " + coll.getString("cust_id_number"));
					reportBean.setFirstDocType("Doc Type : " + coll.getString("doc_sub_type"));
					reportBean.setFirstDepartment("Customer Type : " + coll.getString("cust_type"));					
					reportBean.setFirstCustIDType("Customer Id Type : " + coll.getString("cust_id_type"));					
					reportBean.setFirstDocID("Doc Id : " + docId);
					isUpdate=false;
				}			
				else{					
					reportBean.setBarcodev1(barcodeValue);
					reportBean.setSecondBranch("Branch No :" + branchno);
					reportBean.setSecondCustID("Customer Id : " + coll.getString("cust_id_number"));
					reportBean.setSecondDocType("Doc Type : " + coll.getString("doc_sub_type"));
					reportBean.setSecondDepartment("Customer Type : " + coll.getString("cust_type"));					
					reportBean.setSecondCustIDType("Customer Id Type : " + coll.getString("cust_id_type"));					
					reportBean.setSecondDocID("Doc Id : " + docId);
					isUpdate=true;
				}
				
				//to insert empty values in last item
				if(lastitem){					
					reportBean.setSecondBranch("");
					reportBean.setSecondCustID("");
					reportBean.setSecondDocType("");
					reportBean.setSecondDepartment("");					
					reportBean.setSecondCustIDType("");					
					reportBean.setSecondDocID("");
					isUpdate=true;
				}
					
				if(isUpdate){
					dataBeanList.add(reportBean);					
				}				
			}
				coll.close();
			} 	
		  
			generateJasperReport();			
			  
			}		
			else{	

				successMsg.setLabel("Please select document(s) to Generate Barcode.");				
			}
		}
		catch(Exception e){
			successMsg.setLabel("Error : " + e.getMessage());	
			e.printStackTrace();
			LOGGER.error(e);
		}
	}
	
	@SuppressWarnings("unchecked")
	private void generateJasperReport(){
		
		try{
			LOGGER.debug("Enter into generateJasperReport()");
			JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataBeanList, false);
			Map parameters = new HashMap();
			InputStream inputStream = this.getClass().getClassLoader().
			getResourceAsStream("com/vb/ecm/web/custom/barcode/Barcode.jrxml");
			
			JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
			JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);		
						
			// storing report into repository
			ByteArrayOutputStream objByteArrayOutputStream = new ByteArrayOutputStream();
			JasperExportManager.exportReportToPdfStream(jasperPrint, objByteArrayOutputStream);
			//JasperExportManager.exportReportToPdfFile(jasperPrint, "C:/deploy/" + dateNow + ".pdf");
			
			//date and time stamp
			Calendar currentDate = Calendar.getInstance();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMMdd-HHmmss");
			String dateNow = formatter.format(currentDate.getTime());
			
		    IDfSysObject sysObj = (IDfSysObject) getDfSession().newObject("dm_document");
			sysObj.setObjectName(dateNow);
			sysObj.setContentType("pdf");
			
			if(isFolderExists()){
				
				sysObj.link("/" + rsb.getString("FOLDER_PATH"));
				sysObj.setContent(objByteArrayOutputStream);
				sysObj.save();
				LOGGER.debug("Barcode Generated @"+"/" + rsb.getString("FOLDER_PATH") + "/"+dateNow);
				successMsg.setLabel("Barcode File Generated Successfully @"+"/" + rsb.getString("FOLDER_PATH") +"/"+dateNow);
			}					    

			objs.clear();
			dataBeanList.clear();
			
			//code to open file in "view" component
			ArgumentList newArgs = new ArgumentList();
		    newArgs.add("objectId", sysObj.getObjectId().getId());
		    LOGGER.debug("Launching Barcode pdf in View component");
		    ActionService.execute("view", newArgs, getContext(), this, null);  	    		    
		    LOGGER.debug("Exit from createFolder");
		}
		catch(Exception e){
			successMsg.setLabel("Error : " + e.getMessage());
			e.printStackTrace();
			LOGGER.error(e);
		}
	}
	
	/**
	 * Description : This method is used to create folder (dm_folder) in ECM.
	 * 
	 * @return boolean : true
	 */	
	private boolean createFolder(String folderName, String folderPath) throws Exception {		
		IDfSysObject sysObj = null;
		boolean flag = false;
		
		try {
			LOGGER.debug("Enter into createFolder");
			sysObj = (IDfSysObject)getDfSession().newObject("dm_folder");			
			sysObj.setObjectName(folderName); 
			sysObj.setTitle("Folder Created by Generate Barcode Component");
			sysObj.link("/" + folderPath);
			sysObj.save(); 
			flag = true;			
			LOGGER.debug("Exit from createFolder");
		} catch (DfException e) {			
			e.fillInStackTrace();
		}
		
		return flag;		
	}
	
	/**
	 * Description : This method is used to check the folder existence in ECM.
	 * 
	 * @return boolean : true
	 */	
	private boolean isFolderExists() throws Exception {
		boolean flag = false;
		
		try {
			LOGGER.debug("Enter into isFolderExists");
			IDfFolder isFolderExists = getDfSession().getFolderByPath("/" + rsb.getString("FOLDER_PATH") + 
					"/" + rsb.getString("FOLDER_NAME"));
			 if(isFolderExists!=null){				 
				 flag = true;
				 LOGGER.debug("Folder exist");
			 }
			 else{
				 LOGGER.debug("Folder does not exist, creating new...");
				 //flag = createFolder(rsb.getString("FOLDER_NAME"), rsb.getString("FOLDER_PATH"));
				 flag = true;
				 
			 }
		} catch (DfException e) {			
			e.fillInStackTrace();
		}
		
		return flag;
	}
	

}

